import { defineStore } from 'pinia';
import { ref } from 'vue';


import { usePermissionStore,store } from '@/store';
import type { UserInfo } from '@/types/interface';
import {featchVisitorInfo, featchUserInfo, featchAssetInfo ,getLoginQrcode} from '@/api/user';
import { getPermissionStore } from './permission';
import Cookies from "js-cookie"

const InitUserInfo: UserInfo = {
  user_id: '',
  nick: '', // 用户名，用于展示在页面右上角头像处
  role:0,
  roles: [], // 前端权限模型使用 如果使用请配置modules/permission-fe.ts使用
  avatar: 'https://avatars.githubusercontent.com/Wen1kang',
};


export const useUserStore = defineStore('user', {
  state: () => ({
    token: 'main_token', // 默认token不走权限
    userInfo: { ...InitUserInfo },
    assetInfo: {
      Integral: '-',
      Gold: 0,
      WithdrawAmount: 0,
      CreateCount: 0,
      AlipayWithdrawNo:''
    },
    visibleLogin: ref(false),
    loginQrcodeUrl:''
  }),
  getters: {
    roles: (state) => {
      return state.userInfo?.roles;
    },
  },
  actions: {
    //获取登录二维码
    fetchLoginQrcode(){
      let inviteCode = localStorage.getItem('inviteCode');
      if (inviteCode === null) {
        inviteCode = '';
      }
      const id = Cookies.get('.ServerSentEvents.Guid')??"" ;
      const wsId=localStorage.getItem('websocketId')??"";
      //console.log('sseId='+id+' websocketId='+wsId)
      var that=this
      return new Promise((resolve,reject)=>{
        getLoginQrcode({ websocketId: wsId, inviteCode: '', domain: window.location.host, sseId: id })
          .then((ret) => {
            that.loginQrcodeUrl=ret.url
            resolve({url:ret.url})
          })
          .catch((e) => {
           reject(e)
          });
      })

    },
    async login(userToken:string) {
      this.saveToken(userToken)
      // this.getUserInfo()
      // if(this.userInfo.role>0)
      // {
      //   this.getAssetInfo()
      //   await getPermissionStore().buildAsyncRoutes()
      // }


    },
    async logout() {
      this.token = '';
      this.userInfo = { ...InitUserInfo };
      localStorage.removeItem('token');

    },
    async getUserInfo() {
      this.token = localStorage.getItem('token');
      featchUserInfo()
        .then((ret) => {
          //console.log('getUserInfo()', JSON.stringify(ret));
          this.userInfo = ret;
          localStorage.setItem('userInfo',JSON.stringify(this.userInfo));

        })
        .catch((e) => {
          console.log('featchUserInfo err', JSON.stringify(e));
        });
    },
    async getAssetInfo() {
      featchAssetInfo()
        .then((ret) => {
          console.log('ret', JSON.stringify(ret));
          this.assetInfo = ret;
        })
        .catch((e) => {
          console.log('featchAssetInfo err', JSON.stringify(e));
        });
    },
    //获取登录信息
    async getLoginInfo()
    {
      await this.getUserInfo();
    },

    saveToken(userToken: string) {
      this.token = userToken;
      localStorage.setItem('token', userToken);
    },


  },
  persist: {
    afterRestore: () => {
      const permissionStore = usePermissionStore();
      permissionStore.initRoutes();
    },
    key: 'user',
    paths: ['token'],
  },
});

export function getUserStore() {
  return useUserStore(store);
}
